import Queue

## The reason for GlobalShutdownHook mainly because we cannot unregister the event.
GlobalShutdownHook = dict()

def addShutdownHook(shutdown_mission, name = __name__):
    missions = GlobalShutdownHook.get(name)
    if missions == None:
        missions = []
        GlobalShutdownHook[name] = missions
    missions.append(shutdown_mission)

def selfClean(name = __name__):
    missions = GlobalShutdownHook.get(name)
    if missions == None: return
    for m in missions:
        try:
            m()
        except BaseException as ex:
            print "During running the shutdown hook:"
            print ex
            print "=== Exception Catched and Swallowed ==="

def testException():
    import time
    for i in xrange(10):
        print "Hi"
        try:
            time.sleep(1)
            raise Exception("Hi Exception")
        except Exception as ex:
            print ex
        except KeyboardInterrupt as er:
            print er
        except BaseException as bex:
            print bex

def test1():
    print "Hi"

def test2():
    print "Hello"

if __name__ == "__main__":

##    import lxlxlx
##    print lxlxlx.get__name__()
##    
##    def shutdownAndPrint(): print "Finished Cleaning."
##    addShutdownHook(shutdownAndPrint)
##    print "Running Process0"
##    print "Running Process1"
##    print "Running Process2"
##    selfClean()

    import atexit
    atexit.register(test1)
    atexit.register(test2)
    
